<template>
  <div ref="canvas"></div>
</template>

<script lang="ts" setup>
import * as THREE from "three";
import Stats from "three/examples/jsm/libs/stats.module";
import { GUI } from "three/examples/jsm/libs/lil-gui.module.min.js";
import { TrackballControls } from "three/examples/jsm/controls/TrackballControls";
import { ref, onMounted } from "vue";
import chroma from "chroma-js"
import {initCamera, initDefaultLighting, initWebGLRenderer, setRandomColors} from "@/book/ThreeUtils";
import {OBJLoader} from "three/examples/jsm/loaders/OBJLoader";

const canvas = ref<any>();

const scene = new THREE.Scene();

const renderer = initWebGLRenderer(undefined);

const camera = initCamera(undefined);

const stat = Stats();

const clock = new THREE.Clock();

initDefaultLighting(scene, undefined);

let trackballControls = null;

const loader = new OBJLoader();
loader.load(
    new URL("@/assets/models/city/city.obj", import.meta.url).href,
    (obj) => {
      const scale = chroma.scale(['red', 'green', 'blue']);
      setRandomColors(obj, scale);
      scene.add(obj);
    }
);

const render = () => {
  stat.update();
  trackballControls.update();

  requestAnimationFrame(render);
  renderer.render(scene, camera);
};

onMounted(() => {
  trackballControls = new TrackballControls(camera, canvas.value);
  trackballControls.rotateSpeed = 1.0;
  trackballControls.zoomSpeed = 1.0;
  trackballControls.panSpeed = 1.0;

  canvas.value.appendChild(stat.domElement);
  canvas.value.appendChild(renderer.domElement);

  render();
});

</script>
